<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\common\model\Auth;
use app\user\model\User as UserModel;
use app\mill\model\Client as ClientModel;
use app\mill\model\Order as OrderModel;
use app\mill\model\Give as GiveModel;
use app\mill\model\Archives as ArchivesModel;
use app\mill\model\Finance as FinanceModel;
use app\mill\model\Audit as AuditModel;
use app\admin\model\Config as ConfigModel;
use app\mill\model\Contract as ContractModel;
use app\mill\model\Log as LogModel;
use think\Db;

/**
 * 账单控制器
 * @package app\admin\controller
 */
class Finance extends Admin
{
    public $_status = [
        -1      =>  '未通过',
        0       =>  '待审核',
        1       =>  '已审核',
    ];
    /**
     * 列表页
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['pid','=',0];
        // 数据列表
        $data_list = Db::name('mill_finance')
            ->alias('f')
            ->field('f.*')
            //->leftJoin('mill_order o','o.id=f.order_pid')
            //->leftJoin('mill_client c','c.id=o.client_id')
            ->where($map)
            ->group('f.id')
            ->order('f.id desc')
            ->paginate()
            ->each(function ($v){

                //获取账单应收款信息
                $finance = FinanceModel::financeInfo($v['order_pid']);
                $v = array_merge($v,$finance);

                $v['row_area'] += $v['address_area'];
                $v['address_money'] += $v['audit_money'] + $v['audit_no_money'];

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('财务管理（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_finance') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'f.order_sn', '工程号', 'like'],
                ['text:2', 'f.engineering', '工程名称', 'like'],
                ['text:2', 'f.company', '客户公司', 'like'],
                ['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '工程号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['note', '完成状态'],
                //['note', '备注','popover'],
                ['sum_money', '工程总金额'],
                ['opening_money', '期初结余'],
                ['row_area', '发货量'],
                ['address_money', '发货金额'],
                ['deposit_money', '定金'],
                ['receivable_money', '回款'],
                ['rece_money', '应收款项金额'],
                ['money', '实收款项金额'],
                ['rece_time', '预计收款时间','date'],
                ['handle', '经办人'],
                ['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,$this->_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                //['create_time', '添加日期','date'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('edit1',['title' => '新增','href' => url('add'),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '99%'], 'title' => ['新增', 'font-size:24px;text-align: center;']])
            ->addRightButton('edit1',['title' => '编辑','href' => url('edit',['id'=>'__id__']),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '99%'], 'title' => ['编辑', 'font-size:24px;text-align: center;']])
            ->addRightButton('account', ['title' => '子账单', 'href' => url('account', [ 'pid' => '__id__']), 'icon' => ''])
            ->addRightButton('logList', ['title' => '收款记录', 'href' => url('logList', [ 'finance_id' => '__id__']),'class'=>'btn btn-primary', 'icon' => ''])
            ->addRightButton('invoiceList', ['title' => '开票记录', 'href' => url('invoiceList', [ 'finance_id' => '__id__']),'class'=>'btn btn-primary', 'icon' => ''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 应收汇总统计
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function collect()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['pid','=',0];
        // 数据列表
        $data_list = Db::name('mill_finance')
            ->alias('f')
            ->field('f.*')
            ->where($map)
            //->group('f.id')
            ->order('f.rece_time desc')
            ->paginate()
            ->each(function ($v){

                //获取账单应收款信息
                $finance = FinanceModel::financeInfo($v['order_pid']);
                $v = array_merge($v,$finance);
                $v['row_area'] += $v['address_area'];
                if(empty($v['order_id'])){
                    //$v['order_money'] = $v['sum_money'];
                    //$v['rece_money_sum'] = $v['rece_money'];
                }

                //当前时间
                $v['now_time'] = strtotime(date('Y-m-d'));
                //天数
                $v['day'] = 0;
                //最后一次发货时间
                if(!empty($v['address_time'])){
                    $v['address_time'] = strtotime(date('Y-m-d',$v['address_time']));
                    //天数
                    $v['day'] = intval(($v['now_time']-$v['address_time'])/86400);
                }

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('应收汇总统计') // 页面标题
            ->setTableName('mill_finance') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'f.order_sn', '工程号', 'like'],
                ['text:2', 'f.engineering', '工程名称', 'like'],
                ['text:2', 'f.company', '客户公司', 'like'],
                ['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '工程号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['row_area', '发货量'],
                ['deposit_money', '定金'],
                ['order_money', '货款(元)'],
                ['receivable_money', '回款(元)'],
                ['rece_money_sum', '应收款(元)'],
                ['html_config', '付款节点'],
                ['invoice_money', '已开票金额'],
                ['audit_no_money', '未对账金额'],
                ['audit_money', '对账金额'],
                ['address_time', '最后一次发货时间','date'],
                //['now_time', '当前时间','date'],
                ['day', '天数'],

                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('account', ['title' => '子账单', 'href' => url('account', [ 'pid' => '__id__']), 'icon' => ''])
            ->addRightButton('audit', ['title' => '对账单', 'href' => url('mill/audit/index')."?_s=f.order_sn=__order_sn__&_o=f.order_sn=like", 'icon' => ''])
            ->addRightButton('logList', ['title' => '收款记录', 'href' => url('logList', [ 'finance_id' => '__id__']),'class'=>'btn btn-primary', 'icon' => ''])
            ->addRightButton('invoiceList', ['title' => '开票记录', 'href' => url('invoiceList', [ 'finance_id' => '__id__']),'class'=>'btn btn-primary', 'icon' => ''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 待收款账单
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function payment()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['pid','>',0];
        // 数据列表
        $data_list = Db::name('mill_finance')
            ->alias('f')
            ->field('f.*')
            ->where($map)
            ->group('f.id')
            ->order('f.rece_time desc')
            ->paginate()
            ->each(function ($v){

                //获取账单应收款信息
                $finance = FinanceModel::financeInfo($v['order_pid']);
                $v = array_merge($v,$finance);

                //最后一次发货时间
                if(!empty($v['address_time']))$v['address_time'] = strtotime(date('Y-m-d',$v['address_time']));
                //当前时间
                $v['now_time'] = strtotime(date('Y-m-d'));
                //天数
                $v['day'] = intval(($v['now_time']-$v['address_time'])/86400);

                //90天以内
                $v['day0'] = 0;
                //90-180天
                $v['day1'] = 0;
                //180-360天
                $v['day2'] = 0;
                //一年至两年
                $v['day3'] = 0;
                //两年至三年
                $v['day4'] = 0;
                //三年以上
                $v['day5'] = 0;
                if($v['day'] <= 90)$v['day0'] = $v['rece_money_sum'];
                elseif($v['day'] >= 90 && $v['day'] <= 180)$v['day1'] = $v['rece_money_sum'];
                elseif($v['day'] >= 180 && $v['day'] <= 360)$v['day2'] = $v['rece_money_sum'];
                elseif($v['day'] >= 360 && $v['day'] <= 720)$v['day3'] = $v['rece_money_sum'];
                elseif($v['day'] >= 720 && $v['day'] <= 1080)$v['day4'] = $v['rece_money_sum'];
                else $v['day5'] = $v['rece_money_sum'];

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('待收款账单') // 页面标题
            ->setTableName('mill_finance') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'f.order_sn', '工程号', 'like'],
                ['text:2', 'f.engineering', '工程名称', 'like'],
                ['text:2', 'f.company', '客户公司', 'like'],
                ['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '工程号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['row_area', '发货量'],
                //['deposit_money', '定金'],
                //['order_money', '货款(元)'],
                //['receivable_money', '回款(元)'],
                ['rece_money', '应收款(元)'],
                ['money', '实收款(元)'],
                ['html_config', '付款节点'],
                //['invoice_money', '已开票金额'],
                //['audit_no_money', '未对账金额'],
                //['audit_money', '对账金额'],
                ['address_time', '最后一次发货时间','date'],
                //['now_time', '当前时间','date'],
                //['day', '天数'],
                //['day0', '90天以内'],
                //['day1', '90-180天'],
                //['day2', '180-360天'],
                //['day3', '一年至两年'],
                //['day4', '两年至三年'],
                //['day5', '三年以上'],
                ['rece_time', '预计收款时间','date'],

                ['right_button', '操作', 'btn']
            ])
            //->addRightButton('account', ['title' => '子账单', 'href' => url('account', [ 'pid' => '__id__']), 'icon' => ''])
            //->addRightButton('audit', ['title' => '对账单', 'href' => url('mill/audit/index')."?_s=f.order_sn=__order_sn__&_o=f.order_sn=like", 'icon' => ''])
            //->addRightButton('logList', ['title' => '收款记录', 'href' => url('logList', [ 'finance_id' => '__id__']),'class'=>'btn btn-primary', 'icon' => ''])
            //->addRightButton('invoiceList', ['title' => '开票记录', 'href' => url('invoiceList', [ 'finance_id' => '__id__']),'class'=>'btn btn-primary', 'icon' => ''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 新增
     * @return mixed
     */
    public function add()
    {
        $pid = input('pid');
        $info = [
            'is_pid'        =>  0,
            'order_pid'     =>  0,
            'rece_time'     =>  time(),
        ];
        if(!empty($pid)){
            $finance = Db::name('mill_finance')->where(['id'=>$pid])->find();
            $info['order_pid'] = $finance['order_pid'];
            $info['order_sn'] = $finance['order_sn'];
            $info['engineering'] = $finance['engineering'];
            $info['company'] = $finance['company'];
            $info['handle'] = $finance['handle'];

            $info['pid'] = $pid;
            $info['is_pid'] = 1;
        }

        if ($this->request->isPost()) {
            $data = input();

            // 验证
            $result = $this->validate($data, 'Finance');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            $data['rece_time'] = strtotime($data['rece_time']);
            $data['create_time'] = time();
            $data['update_time'] = time();

            if(!empty($pid))$data['money'] = $data['rece_money'];

            $re = Db::name('mill_finance')->insertGetId($data);
            if ($re){

                //如果是新增的子账单，则更新实收金额
                if(!empty($pid))Db::name('mill_finance')->where(['id'=>$pid])->setInc('money',$data['money']);

                $this->success('操作成功','','_parent_reload');
            }
            $this->error('操作失败');
        }


        return ZBuilder::make('form')
            ->setPageTitle('新增账单') // 页面标题
            ->addHidden('pid')
            ->addHidden('is_pid')
            ->addFormItems([ // 批量添加表单项
                ['text:||||must', 'order_sn', '工程号'],
                ['text:||||must', 'engineering', '工程名称'],
                ['text:||||must', 'company', '客户公司'],
                ['text:||||must', 'handle', '经办人'],
                ['text:||||must', 'sum_money', '工程总金额'],
                ['text:||||must', 'opening_money', '期初结余'],
                ['text:12||||must', 'deposit_money', '定金'],
                ['text:||||must', 'address_area', '发货量'],
                ['text:||||must', 'address_money', '发货金额'],
                ['text:||||must', 'rece_money', '应收款项金额'],
                ['date:||||must', 'rece_time', '预计收款时间'],
                ['text:||||must', 'late_money', '滞纳金'],
                ['date:||||must', 'late_time', '滞纳金退还时间'],
                ['textarea:12||||must', 'note', '项目数据(完成状态)'],

            ])
            ->setTrigger('is_pid','0','sum_money,opening_money,late_money,late_time,deposit_money,address_area,address_money')
            ->setFormData($info)
            ->fetch();
    }
    /**
     * 编辑
     * @param null $id
     * @return mixed
     */
    public function edit($id=null)
    {
        $id = input('id');
        $info = Db::name('mill_finance')
            ->alias('f')
            ->field('f.*')
            ->where(['f.id'=>$id])
            ->find();
        $info['is_pid'] = 1;
        if(empty($info['pid']))$info['is_pid'] = 0;

        if ($this->request->isPost()) {
            $data = input();

            // 验证
            $result = $this->validate($data, 'Finance');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            $data['rece_time'] = strtotime($data['rece_time']);
            $data['update_time'] = time();

            $re = Db::name('mill_finance')->update($data);
            if ($re) $this->success('操作成功','','_parent_reload');
            $this->error('操作失败');
        }


        return ZBuilder::make('form')
            ->setPageTitle('编辑账单') // 页面标题
            ->addHidden('is_pid')
            /*->addFormItems([ // 批量添加表单项
                ['text:||||must', 'order_sn', '工程号'],
                ['text:||||must', 'engineering', '工程名称'],
                ['text:||||must', 'company', '客户公司'],
                ['text:||||must', 'handle', '经办人'],
                ['text:||||must', 'opening_money', '期初结余'],
                ['text:||||must', 'rece_money', '应收款项金额'],
                ['date:||||must', 'rece_time', '预计收款时间'],
                ['textarea:12||||must', 'note', '项目数据(完成状态)'],

            ])*/
            ->addFormItems([ // 批量添加表单项
                ['text:||||must', 'order_sn', '工程号'],
                ['text:||||must', 'engineering', '工程名称'],
                ['text:||||must', 'company', '客户公司'],
                ['text:||||must', 'handle', '经办人'],
                ['text:||||must', 'sum_money', '工程总金额'],
                ['text:||||must', 'opening_money', '期初结余'],
                ['text:12||||must', 'deposit_money', '定金'],
                ['text:||||must', 'address_area', '发货量'],
                ['text:||||must', 'address_money', '发货金额'],
                ['text:||||must', 'rece_money', '应收款项金额'],
                ['date:||||must', 'rece_time', '预计收款时间'],
                ['text:||||must', 'late_money', '滞纳金'],
                ['date:||||must', 'late_time', '滞纳金退还时间'],
                ['textarea:12||||must', 'note', '项目数据(完成状态)'],

            ])
            ->setTrigger('is_pid','0','sum_money,opening_money,late_money,late_time,deposit_money,address_area,address_money')
            ->setFormData($info)
            ->fetch();
    }
    /**
     * 删除
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }
    /**
     * 启用
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }
    /**
     * 禁用
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }
    /**
     * 待审核财务列表页
     * @return mixed
     */
    public function examine()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $map0 = $map01 = $this->getMap();
        // 数据列表
        $data_list = Db::name('mill_finance')
            ->alias('f')
            ->field('f.*')
            ->where([['f.status','<>','1'],['f.pid','=',0]])
            ->where($map)
            ->group('f.id')
            ->order('f.id desc')
            ->paginate();
        //待审核
        $map0[] = ['status','eq','0'];
        $total0 = Db::name('mill_finance')->alias('f')->where($map0)->count();
        //未通过
        $map01[] = ['status','eq','-1'];
        $total01 = Db::name('mill_finance')->alias('f')->where($map01)->count();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('财务审核（待审核'.$total0.'/未通过'.$total01.'）') // 页面标题
            ->setTableName('mill_finance') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'f.order_sn', '工程号', 'like'],
                ['text:2', 'f.engineering', '工程名称', 'like'],
                ['text:2', 'f.company', '客户公司', 'like'],
                ['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '工程号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['note', '完成状态'],
                //['note', '备注','popover'],
                ['rece_money', '应收款项金额'],
                ['rece_time', '预计收款时间','date'],
                ['handle', '经办人'],
                ['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,$this->_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['create_time', '添加日期','date'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('backEnable',['title' => '审核通过','href' => url('backEnable',['id' => '__id__'])."?fieldv=status|1",'class'=>'btn btn-default ajax-get','icon'=>''])
            ->addRightButton('notDisable',['title' => '审核不通过','href' => url('notDisable',['id' => '__id__','field'=>'status']),'icon'=>'','class'=>'btn btn-primary'],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->replaceRightButton(['status' => ['in', '1']], '', 'backEnable,notDisable')
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板

    }
    /**
     * 审核
     */
    public function backEnable()
    {

        $id = input('param.id');
        $fieldv = input('param.fieldv');
        $fieldv = explode('|',$fieldv);

        $info = Db::name('mill_finance')->where('id', $id)->find();

        if (false === Db::name('mill_finance')->where('id', $id)->update([$fieldv[0]=>$fieldv[1]])) {
            $this->error('审核失败，工程ID：'.$id);
        }
        //审核人员
        Db::name('mill_finance')->where('id', $id)->update([$fieldv[0].'_verify_uid'=>UID]);
        //审核时间
        Db::name('mill_finance')->where('id', $id)->update([$fieldv[0].'_time'=>time()]);

        //推送消息
        $status_str = '审核';
        $content = "工程编号<span class='text-primary'>[{$info['order_sn']}]</span>{$status_str}通过";
        $href = admin_url('index')."?_s=f.order_sn={$info['order_sn']}&_o=f.order_sn=like";
        //LogModel::send_message("财务{$status_str}",$content,$href);

        $this->success('提交成功', null, '_parent_reload');
    }
    /**
     * 审核不通过
     */
    public function notDisable()
    {
        $field = input('param.field');
        if ($this->request->isPost()) {
            $data = input();
            $id = input('param.id');
            if (false === Db::name('mill_finance')->where('id', $id)->update([$field=>-1])) {
                $this->error('审核失败，工程ID：'.$id);
            }
            if(!empty($data[$field.'_note']))Db::name('mill_finance')->where('id', $id)->update([$field.'_note'=>$data[$field.'_note']]);
            //审核人员
            Db::name('mill_finance')->where('id', $id)->update([$field.'_verify_uid'=>UID]);
            //审核时间
            Db::name('mill_finance')->where('id', $id)->update([$field.'_time'=>time()]);

            $this->success('操作成功', null, '_parent_reload');
        }

        return ZBuilder::make('form')
            ->setPageTitle('审核不通过原因') // 页面标题
            ->addFormItem('hidden', 'id')
            ->addFormItems([ // 批量添加表单项
                ['textarea', $field.'_note', '[:请输入审核不通过原因]'],
            ])
            ->layout([$field.'_note'=>12])
            ->fetch();
    }

    /**
     * 子账单列表页
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function account()
    {
        $pid = input('pid');
        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['pid','=',$pid];
        // 数据列表
        $data_list = Db::name('mill_finance')
            ->alias('f')
            ->field('f.*')
            //->leftJoin('mill_order o','o.id=f.order_pid')
            //->leftJoin('mill_client c','c.id=o.client_id')
            ->where($map)
            ->group('f.id')
            ->order('f.id desc')
            ->paginate();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('财务管理（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_finance') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'f.order_sn', '档案号', 'like'],
                ['text:2', 'f.engineering', '工程名称', 'like'],
                ['text:2', 'f.company', '客户公司', 'like'],
                ['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '档案号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['note', '完成状态'],
                //['note', '备注','popover'],
                ['rece_money', '应收款项金额'],
                ['rece_time', '预计收款时间','date'],
                ['handle', '经办人'],
                /*['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,$this->_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],*/
                ['create_time', '添加日期','date'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('add',['title' => '新增子账单','href' => url('add',['pid'=>$pid]),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['新增子账单', 'font-size:24px;text-align: center;']])
            ->addRightButton('edit1',['title' => '编辑','href' => url('edit',['id'=>'__id__']),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['编辑', 'font-size:24px;text-align: center;']])
            ->addRightButton('accountLog', ['title' => '调账', 'href' => url('accountLog', [ 'finance_id' => '__id__']), 'icon' => ''])
            //->addRightButton('logList', ['title' => '收款记录', 'href' => url('logList', [ 'pid' => '__id__']),'class'=>'btn btn-primary', 'icon' => ''])
            //->addRightButton('invoiceList', ['title' => '开票记录', 'href' => url('invoiceList', [ 'finance_id' => '__id__']),'class'=>'btn btn-primary', 'icon' => ''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 调账列表页
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function accountLog()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $finance_id = input('finance_id');
        $map = $this->getMap();
        $map[] = ['l.finance_id','=',$finance_id];

        // 数据列表
        $data_list = Db::name('mill_finance_account')
            ->alias('l')
            ->field('l.*,o.engineering,c.company,o.archives_sn')
            ->leftJoin('mill_order o','o.id=l.order_pid')
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->where($map)
            ->group('l.id')
            ->order('l.id desc')
            ->paginate()
            ->each(function ($v){
                $v['money_str'] = FinanceModel::getMoneyStr($v['type'],$v['money'],true);
                $v['money'] = FinanceModel::getMoneyStr($v['type'],$v['money']);

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('调账管理（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_finance_account') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                //['text:2', 'f.order_sn', '工程编号', 'like'],
                //['text:2', 'o.engineering', '工程名称', 'like'],
                //['text:2', 'c.company', '客户公司', 'like'],
                //['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['archives_sn', '档案号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['money_str','调账收入(元)'],
                ['note', '调账说明'],
                ['handle', '经办人'],
                ['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,$this->_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['create_time', '添加日期','date'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('accountAdd',['title' => '新增','href' => url('accountAdd',['finance_id'=>$finance_id]),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['新增', 'font-size:24px;text-align: center;']])
            ->addRightButton('accountEdit',['title' => '编辑','href' => url('accountAdd',['id'=>'__id__']),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['编辑', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 新增
     * @return mixed
     */
    public function accountAdd()
    {
        $id = input('id');
        $finance_id = input('finance_id');

        if ($this->request->isPost()) {
            $data = input();

            // 验证
            $rule = [
                'finance_id|标题' => 'require',
                'type|收入类型' => 'require',
                'money|调账收入' => 'require',
                'handle|经办人' => 'require',
                'note|调账说明' => 'require',
            ];
            $result = $this->validate($data, $rule);
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            $data['update_time'] = time();

            if($id)$re = Db::name('mill_finance_account')->where(['id'=>$id])->update($data);
            else{
                $data['create_time'] = time();
                $re = Db::name('mill_finance_account')->insert($data);
            }

            if ($re) $this->success('操作成功','','_parent_reload');
            $this->error('操作失败');
        }

        if($id)$info = Db::name('mill_finance_account')->where(['id'=>$id])->find();
        else{
            $finance = Db::name('mill_finance')->where(['id'=>$finance_id])->find();

            $info = [
                'finance_id'    =>  $finance_id,
                'order_pid'     =>  $finance['order_pid'],
            ];
        }

        return ZBuilder::make('form')
            ->setPageTitle('新增账单') // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden','finance_id'],
                ['hidden','order_pid'],
                ['radio:||||must','type', '收入类型','',['调减收入','调增收入'],1],
                ['text:||||must', 'money', '调账收入'],
                ['text:||||must', 'handle', '经办人'],
                ['textarea:||||must', 'note', '调账说明'],

            ])
            ->setFormData($info)
            ->fetch();
    }

    /**
     * 待审核调账列表页
     * @return mixed
     */
    public function accountExamine()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['pid','>',0];

        // 获取查询条件
        $map0 = $map01 = $map;

        // 数据列表
        $data_list = Db::name('mill_finance')
            ->alias('f')
            ->field('f.*,o.engineering,c.company,o.order_sn')
            ->leftJoin('mill_order o','o.id=f.order_pid')
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->where([['f.status','<>','1']])
            ->where($map)
            ->group('f.id')
            ->order('f.id desc')
            ->paginate()
            ->each(function ($v){
                $v['money_str'] = FinanceModel::getMoneyStr($v['type'],$v['money'],true);
                $v['money'] = FinanceModel::getMoneyStr($v['type'],$v['money']);

                return $v;
            })
        ;

        //待审核
        $map0[] = ['status','eq','0'];
        $total0 = Db::name('mill_finance')->where($map0)->count();
        //未通过
        $map01[] = ['status','eq','-1'];
        $total01 = Db::name('mill_finance')->where($map01)->count();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('待审核调账（待审核'.$total0.'/未通过'.$total01.'）') // 页面标题
            ->setTableName('mill_finance') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'o.order_sn', '工程号', 'like'],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['text:2', 'c.company', '客户公司', 'like'],
                ['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '工程号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['money_str','调账收入(元)'],
                ['note', '调账说明'],
                ['handle', '经办人'],
                ['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,$this->_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['create_time', '添加日期','date'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('accountEnable',['title' => '审核通过','href' => url('accountEnable',['id' => '__id__','rece_money'=>'__money__'])."?fieldv=status|1",'class'=>'btn btn-default ajax-get','icon'=>''])
            ->addRightButton('accountDisable',['title' => '审核不通过','href' => url('accountDisable',['id' => '__id__','field'=>'status']),'class'=>'btn btn-primary','icon'=>''],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->replaceRightButton(['status' => ['in', '1']], '', 'accountEnable,accountDisable')
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 调账审核
     */
    public function accountEnable()
    {

        $id = input('param.id');
        $fieldv = input('param.fieldv');
        $fieldv = explode('|',$fieldv);
        if (false === Db::name('mill_finance')->where('id', $id)->update([$fieldv[0]=>$fieldv[1]])) {
            $this->error('审核失败，工程ID：'.$id);
        }
        //审核人员
        Db::name('mill_finance')->where('id', $id)->update([$fieldv[0].'_verify_uid'=>UID]);
        //审核时间
        Db::name('mill_finance')->where('id', $id)->update([$fieldv[0].'_time'=>time()]);

        //额外字段更新
        $rece_money = input('rece_money');
        if($rece_money){
            $pid = Db::name('mill_finance')->where(['id'=>$id])->value('pid');
            Db::name('mill_finance')->where('id', $pid)->setInc('rece_money',$rece_money);
        }

        $this->success('提交成功', null, '_parent_reload');
    }
    /**
     * 调账审核不通过
     */
    public function accountDisable()
    {
        $field = input('param.field');
        if ($this->request->isPost()) {
            $data = input();
            $id = input('param.id');
            if (false === Db::name('mill_finance')->where('id', $id)->update([$field=>-1])) {
                $this->error('审核失败，工程ID：'.$id);
            }
            if(!empty($data[$field.'_note']))Db::name('mill_finance')->where('id', $id)->update([$field.'_note'=>$data[$field.'_note']]);
            //审核人员
            Db::name('mill_finance')->where('id', $id)->update([$field.'_verify_uid'=>UID]);
            //审核时间
            Db::name('mill_finance')->where('id', $id)->update([$field.'_time'=>time()]);

            $this->success('操作成功', null, '_parent_reload');
        }

        return ZBuilder::make('form')
            ->setPageTitle('审核不通过原因') // 页面标题
            ->addFormItem('hidden', 'id')
            ->addFormItems([ // 批量添加表单项
                ['textarea', $field.'_note', '[:请输入审核不通过原因]'],
            ])
            ->layout([$field.'_note'=>12])
            ->fetch();
    }

    /**
     * 设定面积表初始价格列表
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function archivesPriceList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['o.archives_status','=',2];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,o.client_id as client_id2,sum(a.number) as number_sum,sum(a.one_area*a.number) as area_sum,o.id as ip_id')
            ->leftJoin('mill_order_archives a','o.id=a.order_id')
            ->where($map)
            ->group('o.id')
            ->order('o.archives_status_time desc,o.id desc')
            ->paginate();

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('面积表计价') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'a.archives_sn', '档案号', 'like'],
                ['select:2', 'o.client_id', '客户公司','','',$company],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['daterange:2', 'o.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['create_time', '工程日期','date'],
                ['archives_sn', '档案号'],
                ['client_id2','客户公司','','',$company],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['number_sum', '产品总量'],
                ['area_sum', '总面积'],
                ['initial_price_status','计价状态','callback',function($value, $data){
                    //$value = Db::name('mill_order_archives_initial_price')->where(['order_id'=>$value])->value('id');
                    //$value = empty($value)?0:1;
                    //$str = FinanceModel::$initial_price_status[$value];
                    $status = OrderModel::status_tag($value,FinanceModel::$initial_price_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['initial_price_status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('archivesPrice',['title' => '计价','href' => url('mill/finance/archivesPrice',['order_id' => '__id__']),'class'=>'btn btn-default','icon'=>''])
            ->addRightButton('archivesPriceShow',['title' => '导出','href' => url('mill/finance/archivesPriceShow',['id' => '__id__','print'=>'2']),'class'=>'btn btn-default disable-dch','icon'=>'','target'=>'_blank'])

            ->replaceRightButton(['initial_price_status' => ['<>','2']],'',['archivesPriceShow'])

            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'engineering'  => 150,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 设定面积表初始价格
     * @return mixed
     */
    public function archivesPrice()
    {

        if(empty($order_id))$order_id = input('order_id');//指定工程
        if(empty($order_id))$this->error('错误操作');

        //判断合同是否已确认付款方式
        $order_pid = Db::name('mill_order')->where(['id'=>$order_id])->value('order_pid');
        $contract = Db::name('mill_order_contract')->where(['order_id'=>$order_pid])->find();
        if(!empty($contract))$contract['finance_config'] = json_decode($contract['finance_config'],true);
        //if(empty($contract))$this->error('合同未审核');
        //if($contract['status'] !== 3)$this->error('财务部未审核合同');

        if ($this->request->isPost()) {
            $data = $this->request->post();

            //更新定价
            if(!empty($data['price_arr'])){
                foreach ($data['price_arr'] as $pav){
                    $pav_id = $pav['id'];
                    unset($pav['id']);

                    if(empty($pav_id))Db::name('mill_order_archives_initial_price')->insert($pav);
                    else Db::name('mill_order_archives_initial_price')->where('id='.$pav_id)->update($pav);
                }

                //更新计价状态
                Db::name('mill_order')->where(['id'=>$pav['order_id']])->update(['initial_price_status'=>1,'initial_price'=>$data['sum_group_price']]);

            }

            /*//自动更新合同收款方式
            $contract_add = [
                'finance_type'          =>  $data['finance_type'],
                'finance_money'         =>  $data['finance_money'],
                'late_money'            =>  $data['late_money'],
                'late_time'             =>  $data['late_time'],
                'finance_config'        =>  json_encode($data['finance_config'],JSON_UNESCAPED_UNICODE),
                'status'                =>  3,
                'update_time'           =>  time(),
            ];

            if(!empty($contract)){
                $contract_add['id'] = $contract['id'];
                ContractModel::update($contract_add);
            }
            else {

                $contract_add['contract_sn'] = "SWAXC".date('Ymd')."-{$order_id}";

                $contract_add['order_id'] = $order_id;
                $contract_add['order_pid'] = $order_pid;
                $contract_add['create_time'] = time();
                $contract_add['create_time'] = time();
                ContractModel::create($contract_add);
            }*/

            $this->success('编辑成功', cookie('__forward__'));
        }

        $table_arr = FinanceModel::fromArchivesShow($order_id);

        $where[] = ['a.order_id','=',$order_id];

        //单价设置
        $order = $table_arr['order_info'];
        $title = "{$order['engineering']} {$order['archives_sn']} 面积表计价";

        $archives_price = Db::name('mill_order_archives_initial_price')->where(['order_id'=>$order['id']])->find();
        if(empty($archives_price)){
            $archives_price['ingots_price'] = '';
            $archives_price['ingots_price2'] = '';
            $archives_price['ingots_time'] = '';
            $archives_price['note'] = '';
        }

        $table_head = $table_arr['head'];
        $table_data = $table_arr['data'];
        $js = $table_arr['js'];

        /*//自动生成合同
        $table_contract = ContractModel::financeTable($contract);
        $table_contract_head = [['收款方式']];
        $table_contract_data = [
            ["[0]
            收款方式：{$table_contract['html_type']}"],
            ["[0]
            {$table_contract['html_config']}"],
        ];
        $js .= '<script type="text/javascript">
                $(function() {
                    $("input[name=\'finance_type\']").click(function() {
                        var val = $(this).val();
                        $(".finance").hide();
                        $(".finance").removeClass("hidden");
                        $(".finance[data-type=\'"+val+"\']").show();
                    });
                })
            </script>';*/

        return ZBuilder::make('form')
            ->setPageTitle($title) // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['number:2', '_ingots_price', '铝锭价', '', $archives_price['ingots_price']],
                ['number:3', '_ingots_price2', '下单铝锭价', '', $archives_price['ingots_price2']],
                ['number:2', '_ingots_price_sum', '差价', '', (floatval($archives_price['ingots_price'])-floatval($archives_price['ingots_price2']))],
                ['text:5', '_ingots_note', '备注', '', $archives_price['note']],
                //['text', '_ingots_time', '铝锭价日期', '', $archives_price['ingots_time']],
                //['complexTable:12', 'contract', '', $table_contract_data, $table_contract_head],
                ['complexTable:12', 'list_archives_group', '', $table_data, $table_head],
            ])
            ->setExtraJs($js)
            ->fetch();
    }
    /**
     * 面积表计价详情（发货单格式）
     * @return mixed
     */
    public function archivesPriceShow()
    {

        $config = new ConfigModel();
        //备注
        $deliver_note = $config->getConfig('mill_deliver_note');

        $id = input('id');//指定订单
        $print = input('print');
        $print2 = $print;
        if($print == 2)$print = 1;

        if($id)$where[] = ['g.order_id','=',$id];
        $where[] = ['g.quality_status','>','-2'];

        $table_fields = ArchivesModel::$fields4;

        unset($table_fields['status']);
        $table_fields['note'] = '备注';

        $fields = '';
        foreach ($table_fields as $k=>$v){
            if($k == 'number')$fields .= ",COUNT(g.id) as number";
            elseif ($k == 'row_area')$fields .= ",(COUNT(g.id)*a.one_area) as row_area";
            elseif($k == 'status'){
                $give_status = GiveModel::$give_status;
                $fields .= ",(CASE";
                foreach ($give_status as $gk=>$gv){
                    $fields .= " WHEN g.{$k}={$gk} THEN '{$gv}' ";
                }
                $fields .= " ELSE '不详' END) AS status";

            }
            elseif ($k == 'note'){
                //$fields .= ",concat(o.batch,'/',a.archives_sn) as note";
                $fields .= ",o.batch as note";
            }
            else $fields .= ",a.{$k}";
        }
        $fields = trim($fields,',');

        $group = 'a.id';
        $join = [['mill_order_archives_give g','a.id=g.archives_id','left'],['mill_order o','a.order_id=o.id','left']];

        $table_title = '';

        $table_head = [array_values($table_fields)];

        $table_data = [];
        $table_data_list = ArchivesModel::getList($id,$fields.',a.id,a.order_id,a.order_pid,o.archives_sign_time,group_concat(g.id) as give_ids,group_concat(g.address_sn) as give_address_sns,g.address_sn as give_address_sn,(a.weld*count(g.id)) as weld,(a.slot*count(g.id)) as slot','a.order_id asc,CONVERT (REPLACE(a.sort,\'#\',\'999999\'),signed) ASC',$group,$join,$where);

        if($table_data_list){
            $_order_id = 0;
            $_number = 0;
            $_row_area = 0;
            $_slot = 0;
            $_weld = 0;
            $_sign_time = '';
            $table_group_data_type_sarr = [];
            $tgd_type_sarr['number'] = 0;
            $tgd_type_sarr['row_area'] = 0;
            $tgd_type_sarr['slot'] = 0;
            $tgd_type_sarr['weld'] = 0;
            $give_address_sn_w = '';
            $i = 1;
            foreach ($table_data_list as $tdk=>$tdv){
                if(empty($order_pid))$order_pid = $tdv['order_pid'];
                if($_order_id == 0)$_order_id = $tdv['order_id'];
                if($tdv['give_address_sn'])$give_address_sn_w = $tdv['give_address_sn'];


                if(isset($tdv['slot'])){
                    $tgd_type_sarr['slot'] += floatval($tdv['slot']);
                    $_slot += floatval($tdv['slot']);
                    $table_group_data_type_sarr[$tdv['order_id']]['slot'] = $_slot;
                }
                if(isset($tdv['weld'])){
                    $tgd_type_sarr['weld'] += floatval($tdv['weld']);
                    $_weld += floatval($tdv['weld']);
                    $table_group_data_type_sarr[$tdv['order_id']]['weld'] = $_weld;
                }

                if($print != 1){
                    //合计开槽
                    if(isset($tdv['slot'])){
                        //$tgd_type_sarr['slot'] += $tdv['slot'];
                        $tdv['slot'] = '[0]
                    <input type="hidden" name="archives_arr['.$i.'][id]" value="'.$tdv['id'].'">
                    <input type="hidden" name="archives_arr['.$i.'][give_ids]" value="'.$tdv['give_ids'].'">
                    <input class="form-control area" type="number" name="archives_arr['.$i.'][slot]" value="'.$tdv['slot'].'" data-area-type="slot" data-group="group_'.md5($tdv['thickness'].'|||'.$tdv['color'].'|||'.$tdv['model'].'|||slot').'" data-i="'.$i.'">';
                    }
                    //合计焊缝
                    if(isset($tdv['weld'])){
                        //$tgd_type_sarr['weld'] += $tdv['weld'];
                        $tdv['weld'] = '[0]
                    <input type="hidden" name="archives_arr['.$i.'][id]" value="'.$tdv['id'].'">
                    <input type="hidden" name="archives_arr['.$i.'][give_ids]" value="'.$tdv['give_ids'].'">
                    <input class="form-control area" type="number" name="archives_arr['.$i.'][weld]" value="'.$tdv['weld'].'" data-area-type="weld" data-group="group_'.md5($tdv['thickness'].'|||'.$tdv['color'].'|||'.$tdv['model'].'|||weld').'" data-i="'.$i.'">';
                    }
                }

                if($_order_id != $tdv['order_id']){

                    $table_data[] = ['小计[1:1]','','','','',$_number,'',$_row_area,'',$_slot,$_weld,'','',$_sign_time,];
                    $_order_id = $tdv['order_id'];
                    $_number = 0;
                    $_row_area = 0;
                    $_slot = 0;
                    $_weld = 0;

                }

                $_number += $tdv['number'];
                $_row_area += $tdv['row_area'];
                $tgd_type_sarr['number'] += $tdv['number'];
                $tgd_type_sarr['row_area'] += $tdv['row_area'];
                //$_sign_time = !empty($tdv['archives_sign_time'])?date('Y.m.d',$tdv['archives_sign_time']):'';
                //板厚统计
                if(!isset($table_group_data_type_sarr[$tdv['order_id']]['thickness'][$tdv['thickness']]))$table_group_data_type_sarr[$tdv['order_id']]['thickness'][$tdv['thickness']] = 0;
                $table_group_data_type_sarr[$tdv['order_id']]['thickness'][$tdv['thickness']] += $tdv['row_area'];
                unset($tdv['id']);
                unset($tdv['order_id']);
                unset($tdv['order_pid']);
                unset($tdv['archives_sign_time']);
                unset($tdv['give_ids']);
                unset($tdv['give_address_sns']);
                unset($tdv['give_address_sn']);
                $table_data[] = $tdv;

                if($i == count($table_data_list)){
                    $table_data[] = ['小计[1:1]','','','','',$_number,'',$_row_area,'',(empty($_slot)?'':$_slot),(empty($_weld)?'':$_weld),'','',$_sign_time,];
                    $table_data[] = ['合计[1:1]','','','','',$tgd_type_sarr['number'],'',$tgd_type_sarr['row_area'],'',(empty($tgd_type_sarr['slot'])?'':$tgd_type_sarr['slot']),(empty($tgd_type_sarr['weld'])?'':$tgd_type_sarr['weld']),'','','',];

                }

                $i++;
            }
            //打印
            if($print != 1){
                $table_data[] = ["<div style='text-align: right'>合计数量：<a style='font-size: 25px;'>".Db::name('mill_order_archives_give')->alias('g')->where($where)->count()."</a>  合计面积(M²)：<a style='font-size: 25px;'>".Db::name('mill_order_archives_give')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where($where)->sum('a.one_area')."[14:1]</a></div>"];
            }

        }
        $table_group_head = [['板厚(MM)','颜色','铝板版型','合计件数','合计面积(M²)']];
        $table_group_field = 'a.order_id,o.batch,a.thickness,a.color,a.model,SUM(g.number) AS number_sum,SUM(a.one_area) AS one_area_sum,SUM(a.slot) AS slot_sum,SUM(a.weld) AS weld_sum,group_concat(DISTINCT a.id) as archives_ids';
        /*//未发货
        if(!($status_arr[0]=='=')){
            $table_group_field = 'a.thickness,a.color,a.model,SUM(g.number) AS number_sum,SUM(a.one_area) AS one_area_sum';
        }*/
        $table_group_data = ArchivesModel::getList($id,$table_group_field,'a.archives_sn asc,a.thickness asc,a.color asc,a.model asc','a.order_id,a.thickness,a.color,a.model',$join,$where);

        $hideBtn = ['submit'];
        $html_top = '';
        $js = '';
        //已发货-加入单价设置

        $join[] = ['mill_client c','c.id=o.client_id','left'];
        $join[] = ['mill_car ca','ca.id=g.car_id','left'];
        $order = Db::name('mill_order_archives')
            ->alias('a')
            ->field('o.*,group_concat(o.archives_sn) as archives_sns,group_concat(o.batch) as batchs,c.company,c.mobile as c_mobile,ca.plate_number')
            ->join($join)
            ->where($where)
            ->order('a.order_id asc,a.sort asc')
            ->find();
        $title = "{$order['engineering']}{$order['archives_sns']}";

        $hideBtn = [];

        $table_group_head = [['板厚(MM)','颜色','铝板版型','数量','合计面积(M²)','单价(元)','金额(元)']];
        if(!empty($table_group_data)){

            $address_sn = '';
            $address_date = '';
            $table_group_data_new = [];
            //小计
            $_sum_group_number = 0;
            $_sum_group_area = 0;
            $_sum_group_price = 0;
            //总计
            $sum_group_number = 0;
            $sum_group_area = 0;
            $sum_group_price = 0;
            $_batch = '';
            $i = 0;
            $ii = 0;

            foreach ($table_group_data as $tgk=>$tgd){

                if(!isset($tgd['archives_ids']))break;
                $i++;
                $ii++;
                if(isset($table_group_data[$i]['order_id']))$_order_id = $table_group_data[$i]['order_id'];
                else $_order_id = 0;
                if(isset($tgd['batch']))$_batch = $tgd['batch'];


                //按批次进行面积表计价
                $tgd_sum_arr = Db::name('mill_order_archives')->field('SUM(slot) AS slot_sum,SUM(weld) AS weld_sum')->where([['id','in',$tgd['archives_ids']]])->find();
                $tgd['slot_sum'] = $tgd_sum_arr['slot_sum'];
                $tgd['weld_sum'] = $tgd_sum_arr['weld_sum'];

                $tgd_where = ['address_sn'=>$address_sn,'order_id'=>$tgd['order_id'],'order_pid'=>$order_pid,'color'=>$tgd['color'],'thickness'=>$tgd['thickness'],'model'=>$tgd['model']];

                if($print != 1){
                    //合计开槽
                    $tgd['slot_sum'] = '[0]
                    <div id="group_'.md5($tgd['order_id'].'|||'.$tgd['thickness'].'|||'.$tgd['color'].'|||'.$tgd['model'].'|||slot').'"><input type="hidden" name="price_arr['.$ii.'][slot]" value="'.$tgd['slot_sum'].'"><div>'.$tgd['slot_sum'].'</div></div>';
                    //合计焊缝
                    $tgd['weld_sum'] = '[0]
                    <div id="group_'.md5($tgd['order_id'].'|||'.$tgd['thickness'].'|||'.$tgd['color'].'|||'.$tgd['model'].'|||weld').'"><input type="hidden" name="price_arr['.$ii.'][weld]" value="'.$tgd['weld_sum'].'"><div>'.$tgd['weld_sum'].'</div></div>';
                }
                //----------------------单价-------------------------
                $archives_price = Db::name('mill_order_archives_price')->where($tgd_where)->find();
                $price = 0;
                $price_id = 0;
                $price_time = time();
                $price_order_id = $tgd['order_id'];
                $price_order_pid = $order_pid;
                $price_address_sn = $address_sn;
                $price_address_date = $address_date;
                if(!empty($archives_price)){
                    $price_id = $archives_price['id'];
                    $price_order_id = $archives_price['order_id'];
                    $price_order_pid = $archives_price['order_pid'];
                    $price = $archives_price['price'];
                    $price_address_sn = $archives_price['address_sn'];
                    $price_time = $archives_price['create_time'];
                    $price_address_date = $archives_price['address_date'];
                }
                elseif(!empty($tgd['order_id'])){
                    //设置初始价
                    $tgd_where = ['order_id'=>$tgd['order_id'],'color'=>$tgd['color'],'thickness'=>$tgd['thickness'],'model'=>$tgd['model']];
                    $price = Db::name('mill_order_archives_initial_price')->where($tgd_where)->value('price');
                    $price = floatval($price);
                }
                $price_html = '[0]
                <input type="hidden" name="price_arr['.$ii.'][id]" value="'.$price_id.'">
                <input type="hidden" name="price_arr['.$ii.'][order_id]" value="'.$price_order_id.'">
                <input type="hidden" name="price_arr['.$ii.'][order_pid]" value="'.$price_order_pid.'">
                <input type="hidden" name="price_arr['.$ii.'][address_sn]" value="'.$price_address_sn.'">
                <input type="hidden" name="price_arr['.$ii.'][address_date]" value="'.$price_address_date.'">
                <input type="hidden" name="price_arr['.$ii.'][create_time]" value="'.$price_time.'">
                <input type="hidden" name="price_arr['.$ii.'][color]" value="'.$tgd['color'].'">
                <input type="hidden" name="price_arr['.$ii.'][thickness]" value="'.$tgd['thickness'].'">
                <input type="hidden" name="price_arr['.$ii.'][model]" value="'.$tgd['model'].'">
                <input class="form-control group_price" type="number" name="price_arr['.$ii.'][price]" value="'.$price.'" data-one_area_sum="'.$tgd['one_area_sum'].'"  data-i="'.$ii.'">
            ';
                $tgd['price'] = $price_html;
                $tgd['price_sum'] = '<span class="group_price_all" id="area_sum_'.$ii.'">'.round($price*$tgd['one_area_sum']).'</span>';
                //打印
                if($print == 1){
                    $tgd['price'] = $price;
                    $tgd['price_sum'] = strip_tags($tgd['price_sum']);
                }
                $sum_group_number += $tgd['number_sum'];
                $sum_group_area += $tgd['one_area_sum'];
                $sum_group_price += round($price*$tgd['one_area_sum']);
                $_sum_group_number += $tgd['number_sum'];
                $_sum_group_area += $tgd['one_area_sum'];
                $_sum_group_price += round($price*$tgd['one_area_sum']);


                //$tgd['slot_sum'] = '';
                unset($tgd['order_id']);
                unset($tgd['batch']);
                unset($tgd['slot_sum']);
                unset($tgd['weld_sum']);
                unset($tgd['archives_ids']);
                $table_group_data_new[] = $tgd;

                //按批次分组计价
                if($_order_id != $price_order_id){

                    //-----------------------------其他合计计价---------------------------------
                    //类型 0:面积价 1:铝锭价 2:开槽 3: 焊缝 4:矩管
                    $tgd_type_arr = [
                        //合计开槽
                        ['field'=>'slot','title'=>'合计开槽(M)','type'=>2,'sum_eq'=>2],
                        //合计焊缝
                        ['field'=>'weld','title'=>'合计焊缝(M)','type'=>3,'sum_eq'=>2],
                    ];
                    if(count($tgd_type_arr)>0){
                        foreach ($tgd_type_arr as $ttav){

                            $ii++;
                            $ld_field = $ttav['field'];
                            $ld_title = $ttav['title'];
                            $ld_sum_eq = $ttav['sum_eq'];
                            $ld_type = $ttav['type'];//类型 0:面积价 1:铝锭价 2:开槽 3: 焊缝 4:矩管

                            $price_arr_where = ['address_sn'=>$address_sn,'order_id'=>$price_order_id,'order_pid'=>$order_pid,'type'=>$ld_type];
                            $tgpv = Db::name('mill_order_archives_price')->where($price_arr_where)->find();
                            if(empty($tgpv) && !empty($price_order_id)){
                                //设置初始价
                                $tgpv['price'] = Db::name('mill_order_archives_initial_price')->where(['order_id'=>$price_order_id,'type'=>$ld_type])->value('price');
                                $tgpv['price'] = floatval($tgpv['price']);
                            }

                            $ld_id = !empty($tgpv['id'])?$tgpv['id']:'';
                            $ld_order_id = !empty($tgpv['order_id'])?$tgpv['order_id']:$price_order_id;
                            $ld_order_pid = !empty($tgpv['order_pid'])?$tgpv['order_pid']:$order_pid;
                            $ld_address_sn = !empty($tgpv['address_sn'])?$tgpv['address_sn']:$address_sn;
                            $ld_address_date = !empty($tgpv['address_date'])?$tgpv['address_date']:$address_date;
                            $ld_time = !empty($tgpv['create_time'])?$tgpv['create_time']:time();
                            $ld_pirce = !empty($tgpv['price'])?$tgpv['price']:0;
                            $ld_row_area = $table_group_data_type_sarr[$ld_order_id][$ld_field];

                            if(!empty($ld_row_area)){
                                $ld_price_sum = round($ld_row_area*$ld_pirce);//四舍五入取整

                                $ld_field_html = '<div class="'.$ld_field.'_sum">'.$ld_row_area.'</div>';
                                $ld_input_html = '[0]
                
            <input type="hidden" name="price_arr['.$ii.'][id]" value="'.$ld_id.'">
            <input type="hidden" name="price_arr['.$ii.'][order_id]" value="'.$ld_order_id.'">
            <input type="hidden" name="price_arr['.$ii.'][order_pid]" value="'.$ld_order_pid.'">
            <input type="hidden" name="price_arr['.$ii.'][address_sn]" value="'.$ld_address_sn.'">
            <input type="hidden" name="price_arr['.$ii.'][address_date]" value="'.$ld_address_date.'">
            <input type="hidden" name="price_arr['.$ii.'][create_time]" value="'.$ld_time.'">
            <input type="hidden" name="price_arr['.$ii.'][type]" value="'.$ld_type.'">
            <input type="hidden" name="price_arr['.$ii.'][row_area]" value="'.$ld_row_area.'" class="'.$ld_field.'_row_area">
            
            <input class="form-control '.$ld_field.'_val group_price" type="number" name="price_arr['.$ii.'][price]" value="'.$ld_pirce.'" data-one_area_sum="'.$ld_row_area.'"  data-i="'.$ii.'">
            
            ';
                                $ld_price_html = '<span class="group_price_all" id="area_sum_'.$ii.'">'.$ld_price_sum.'</span>';

                                $new_ttav = ['',$ld_title,'','','',$ld_input_html,$ld_price_html];
                                $new_ttav[$ld_sum_eq] = $ld_field_html;
                                //打印
                                if($print == 1){
                                    $ld_field_html = $ld_row_area;
                                    $ld_input_html = "[1]".$ld_pirce;
                                    $ld_price_html = $ld_price_sum;

                                    $ld_title .= "[1]";

                                    //var_dump($ld_sum_eq);exit;
                                    $new_ttav = ['',$ld_title,'','','',$ld_input_html,$ld_price_html];
                                    $new_ttav[$ld_sum_eq] = $ld_field_html;
                                }


                                $table_group_data_new[] = $new_ttav;
                                $sum_group_price += $ld_price_sum;
                                $_sum_group_price += $ld_price_sum;
                            }


                        }
                    }
                    //铝锭价
                    $price_arr_where = ['address_sn'=>$address_sn,'order_id'=>$price_order_id,'order_pid'=>$order_pid,'type'=>1];
                    $table_group_price_arr = Db::name('mill_order_archives_price')->where($price_arr_where)->select();

                    //设置初始价
                    if(empty($table_group_price_arr) && !empty($price_order_id)){
                        $table_group_price_arr = Db::name('mill_order_archives_initial_price')->field('title,row_area,price')->where(['order_id'=>$price_order_id,'type'=>1])->select();
                    }

                    //根据板厚数量生成
                    $tgp_thickness_arr = $table_group_data_type_sarr[$price_order_id]['thickness'];
                    $tgp_count = count($table_group_price_arr)>0?count($table_group_price_arr):count($tgp_thickness_arr);
                    for($pi=0;$pi<$tgp_count;$pi++){
                        $tgpv = !empty($table_group_price_arr[$pi])?$table_group_price_arr[$pi]:'';

                        $_thickness = key($tgp_thickness_arr);

                        $ii++;
                        $ld_id = !empty($tgpv['id'])?$tgpv['id']:'';
                        $ld_order_id = !empty($tgpv['order_id'])?$tgpv['order_id']:$price_order_id;
                        $ld_order_pid = !empty($tgpv['order_pid'])?$tgpv['order_pid']:$order_pid;
                        $ld_address_sn = !empty($tgpv['address_sn'])?$tgpv['address_sn']:$address_sn;
                        $ld_address_date = !empty($tgpv['address_date'])?$tgpv['address_date']:$address_date;
                        $ld_time = !empty($tgpv['create_time'])?$tgpv['create_time']:time();
                        $ld_title = !empty($tgpv['title'])?$tgpv['title']:'';
                        $ld_thickness = !empty($tgpv['thickness'])?$tgpv['thickness']:$_thickness;
                        $ld_pirce = !empty($tgpv['price'])?$tgpv['price']:0;
                        $ld_area = !empty($tgpv['row_area'])?$tgpv['row_area']:(isset($tgp_thickness_arr[$_thickness])?$tgp_thickness_arr[$_thickness]:'');
                        $ld_type = 1;//类型 0:面积价 1:铝锭价 2:其他价
                        $ld_price_sum = round($ld_pirce*floatval($ld_area));//四舍五入，取整

                        $ld_thickness_html = '[0]
            <input class="form-control" type="text" placeholder="请填写板厚" name="price_arr['.$ii.'][thickness]" value="'.$ld_thickness.'" data-i="'.$ii.'">';

                        $ld_input_html = '[0]
            <input class="form-control area" type="number" name="price_arr['.$ii.'][row_area]" value="'.$ld_area.'" data-area-type="group_row_area_'.$ii.'" data-toAreaSum="no" data-i="'.$ii.'">';

                        $ld_field_html = '[0]
            <input type="hidden" name="price_arr['.$ii.'][id]" value="'.$ld_id.'">
            <input type="hidden" name="price_arr['.$ii.'][order_id]" value="'.$ld_order_id.'">
            <input type="hidden" name="price_arr['.$ii.'][order_pid]" value="'.$ld_order_pid.'">
            <input type="hidden" name="price_arr['.$ii.'][address_sn]" value="'.$ld_address_sn.'">
            <input type="hidden" name="price_arr['.$ii.'][address_date]" value="'.$ld_address_date.'">
            <input type="hidden" name="price_arr['.$ii.'][create_time]" value="'.$ld_time.'">
            <input type="hidden" name="price_arr['.$ii.'][type]" value="'.$ld_type.'">
                
            <input class="form-control" type="text" placeholder="请填写铝锭价标题" name="price_arr['.$ii.'][title]" value="'.$ld_title.'" data-i="'.$ii.'">';
                        $ld_area_html = '[0]
            <input class="form-control group_price group_row_area_'.$ii.'_val" type="number" name="price_arr['.$ii.'][price]" value="'.$ld_pirce.'" data-one_area_sum="'.$ld_area.'" data-i="'.$ii.'">
            
            ';
                        $ld_price_html = '<span class="group_price_all" id="area_sum_'.$ii.'">'.$ld_price_sum.'</span>';


                        //打印
                        if($print == 1){
                            if(!empty($ld_title)){
                                $ld_thickness_html = "[1]".$ld_thickness;
                                $ld_field_html = "[1]".$ld_title;
                                $ld_input_html = "[1]".$ld_area;
                                $ld_area_html = "[1]".$ld_pirce;
                                $ld_price_html = strip_tags($ld_price_html);

                                $table_group_data_new[] = [$ld_thickness_html,$ld_field_html,$ld_input_html,'','',$ld_area_html,$ld_price_html];
                            }

                        }
                        else{
                            $table_group_data_new[] = [$ld_thickness_html,$ld_field_html,$ld_input_html,'','',$ld_area_html,$ld_price_html];
                        }


                        $sum_group_price += $ld_price_sum;
                        $_sum_group_price += $ld_price_sum;

                        unset($tgp_thickness_arr[$_thickness]);
                    }

                    //小计
                    $new_ttav = ["{$_batch}合计",'','',$_sum_group_number,$_sum_group_area,'',$_sum_group_price];
                    $table_group_data_new[] = $new_ttav;

                    //合计
                    if($i == count($table_group_data)){
                        $new_ttav = ["总计",'','',$sum_group_number,$sum_group_area,'',$sum_group_price];
                        $table_group_data_new[] = $new_ttav;
                    }


                    $_sum_group_number = 0;
                    $_sum_group_area = 0;
                    $_sum_group_price = 0;
                }


            }


            if($print != 1)$table_group_data[] = ["<div style='text-align: right'>合计数量：<a style='font-size: 25px;'>".$sum_group_number."</a>  合计面积(M²)：<a style='font-size: 25px;'>".$sum_group_area."</a>  合计开槽：<a id='sum_group_slot' style='font-size: 25px;'>".$tgd_type_sarr['slot']."</a>  合计焊缝：<a id='sum_group_weld' style='font-size: 25px;'>".$tgd_type_sarr['weld']."</a>  合计金额(元)：<a id='sum_group_price' style='font-size: 25px;'>".$sum_group_price."[9:1]</a></div>"];

        }

        //--------------------------------批次----------------------------------------
        $batchs = implode(',',array_unique(explode(',',$order['batchs'])));
        $batchs_str = str_replace('批,',",",$batchs);
        $batchs_str = str_replace(',第',",",$batchs_str);
        $batchs_str = str_replace(',',"/",$batchs_str);
        //------------------------------订单编号--------------------------------------
        //项目名称只保留前8位
        $order['engineering'] = mb_substr($order['engineering'],0,8);
        if(!empty($order['engineering_full']))$order['engineering'] = $order['engineering_full'];
        $archives_sns = array_unique(explode(',',$order['archives_sns']));
        $archives_sns_head = '';
        $archives_sns_str = "";
        $archives_sns_str1 = "";
        $archives_sns_str1_arr = [];
        $archives_sns_str2 = "";
        //$archives_sns_str = implode(',',$archives_sns);

        //打印
        if($print == 1){
            foreach ($archives_sns as $asv){
                $asv_arr = explode('-',$asv);

                $archives_sns_str = $asv_arr[0];
                if(!in_array($asv_arr[1],$archives_sns_str1_arr))$archives_sns_str1 .= ' .'.$asv_arr[1];
                $archives_sns_str2 .= '、'.$asv_arr[2].'P';

                $archives_sns_str1_arr[] = $asv_arr[1];

                /*if(count($asv_arr) == 2){
                    if($archives_sns_head == ''){
                        $archives_sns_head = $asv_arr[0];
                        $archives_sns_str .= "{$asv_arr[0]}-{$asv_arr[1]}";
                    }
                    else{
                        if($archives_sns_head == $asv_arr[0])$archives_sns_str .= "/{$asv_arr[1]}";
                        else{
                            $archives_sns_str .= "/{$asv_arr[0]}-{$asv_arr[1]}";
                            $archives_sns_head = $asv_arr[0];
                        }
                    }

                }
                else $archives_sns_str .= "/{$asv_arr[0]}";*/

            }
            $archives_sns_str = "{$archives_sns_str}-".trim($archives_sns_str1,' .')." ({$order['engineering']})".trim($archives_sns_str2,'、');

            //缩放比例
            $table_scaling = 1;
            $table_style = '-webkit-transform: scale('.$table_scaling.');';
            $html = '<html><style>th{font-size: 5px;font-weight: normal;}td{font-size: 5px;}</style><title>'.config('web_site_title').'</title><body style="margin: 4px;">';

            //头部
            $html .= '<table border="1" style="border-collapse: collapse;width: '.(21/$table_scaling).'cm;text-align: center;transform-origin: 0 0;"><thead>
                    <tr><th colspan="14" style="font-size: 18px;font-weight: bold;"><img style="width: 31px;margin-bottom: -10px;" src="'.config('template.tpl_replace_string')['__ADMIN_IMG__'].'/logo2.jpg">'.config('web_site_title').'</th></tr>
                    <tr><th colspan="14" style="'.$table_style.'">发货清单日期：'.$address_date.'</th></tr>
                    <tr>
                        <th colspan="2" style="'.$table_style.'">客户名称：</th>
                        <th colspan="4" style="'.$table_style.'">'.$order['company'].'</th>
                        <th colspan="6" style="'.$table_style.'text-align: left;">档案号：'.$archives_sns_str.'</th>
                        <th colspan="2" style="'.$table_style.'text-align: left;">发货批次：'.$batchs_str.'</th>
                    </tr>
                    <tr>
                        <th colspan="2" style="'.$table_style.'">工程名称：</th>
                        <th colspan="4" style="'.$table_style.'">'.$order['engineering'].'</th>
                        <th colspan="6" style="'.$table_style.'text-align: left;">经办人：'.$order['archives_handle'].'</th>
                        <th colspan="2" style="'.$table_style.'text-align: left;">发货单号：</th>
                    </tr>
                ';

            //面积信息-头
            $html .= '<tr>';
            $i=0;
            foreach ($table_fields as $tk=>$tv){
                if($tk == 'status')$tv = '&nbsp;&nbsp;&nbsp;备注&nbsp;&nbsp;&nbsp;';
                $html .= '<th style="'.$table_style.'">'.$tv.'</th>';
                $i++;
            }
            $html .= '</tr>';
            $html .= '</tr></thead>';

            $html .= '<tbody>';
            //面积信息-体
            $row_number = 0;//合计，数量
            $row_area = 0;//合计，面积'
            foreach ($table_data as $td){
                if(isset($td['sort'])){
                    $html .= '<tr>
                    <td style="'.$table_style.'">'.$td['sort'].'</td>
                    <td style="'.$table_style.'">'.$td['model_sn'].'</td>
                    <td style="'.$table_style.'">'.$td['page'].'</td>
                    <td style="'.$table_style.'">'.$td['long'].'</td>
                    <td style="'.$table_style.'">'.$td['high'].'</td>
                    <td style="'.$table_style.'">'.$td['number'].'</td>
                    <td style="'.$table_style.'">'.$td['one_area'].'</td>
                    <td style="'.$table_style.'">'.$td['row_area'].'</td>
                    <td style="'.$table_style.'">'.$td['color'].'</td>
                    <td style="'.$table_style.'">'.(empty($td['slot'])?'':$td['slot']).'</td>
                    <td style="'.$table_style.'">'.(empty($td['weld'])?'':$td['weld']).'</td>
                    <td style="'.$table_style.'">'.$td['thickness'].'</td>
                    <td style="'.$table_style.'">'.$td['model'].'</td>
                    <td style="'.$table_style.'">'.$td['note'].'</td>
                </tr>';
                    $row_number+=$td['number'];
                    $row_area+=$td['row_area'];
                }
                else{
                    $html .= '<tr>';
                    foreach ($td as $tdk=>$tdv){

                        $v = OrderModel::tableParseCell($tdv);

                        $html .= '
                        <td style="'.$table_style.'" rowspan="'.$v['rowspan'].'" colspan="'.$v['colspan'].'">'.$v['value'].'</td>
                        ';
                    }

                    $html .= '</tr>';

                }

            }

            /*//面积信息合计
            $html .= '
                <tr>
                    <td style="'.$table_style.'" colspan="2">合计</td>
                    <td style="'.$table_style.'"></td>
                    <td style="'.$table_style.'">'.$row_number.'</td>
                    <td style="'.$table_style.'"></td>
                    <td style="'.$table_style.'">'.$row_area.'</td>
                    <td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
                </tr>';*/

            //价格-头
            $html .= '<tr>
                    <th style="'.$table_style.'">'.$table_group_head[0][0].'</th>
                    <th style="'.$table_style.'">'.$table_group_head[0][1].'</th>
                    <th style="'.$table_style.'">'.$table_group_head[0][2].'</th>
                    <th style="'.$table_style.'">'.$table_group_head[0][3].'</th>
                    <th style="'.$table_style.'">'.$table_group_head[0][4].'</th>
                    <th style="'.$table_style.'">'.$table_group_head[0][5].'</th>
                    <th style="'.$table_style.'">'.$table_group_head[0][6].'</th>
                </tr>';

            //价格-体
            foreach ($table_group_data_new as $tgv){
                $rowspan = '';
                $rowspan2 = '';

                if(isset($tgv['thickness']) && 1==2){
                    $html .= '<tr class="group">
                        <td style="'.$table_style.'" '.$rowspan.'>'.$tgv['thickness'].'</td>
                        <td style="'.$table_style.'" '.$rowspan2.'>'.$tgv['color'].'</td>
                        <td style="'.$table_style.'">'.$tgv['model'].'</td>
                        <td style="'.$table_style.'">'.$tgv['number_sum'].'</td>
                        <td style="'.$table_style.'">'.$tgv['one_area_sum'].'</td>
                        <td style="'.$table_style.'">'.$tgv['price'].'</td>
                        <td style="'.$table_style.'">'.$tgv['price_sum'].'</td>
                    </tr>';
                }
                else{
                    $html .= '<tr>';
                    foreach ($tgv as $tdk=>$tdv){

                        $v = OrderModel::tableParseCell($tdv);

                        $html .= '
                        <td style="'.$table_style.'" rowspan="'.$v['rowspan'].'" colspan="'.$v['colspan'].'">'.$v['value'].'</td>
                        ';
                    }

                    $html .= '</tr>';
                }

            }

            //备注
            $deliver_note = str_replace("\r\n","</br>",$deliver_note);
            $html .= '<tr><td style="'.$table_style.'" colspan="2">备注：</td><td colspan="12" style="'.$table_style.'text-align: left">'.$deliver_note.'  指定收货人联系方式：</br></br></br></td></tr>';

            //发货信息
            //<td colspan="3" style="text-align: left">'.$order['nickname'].'</td>
            //<td colspan="3" style="text-align: left">'.$order['c_mobile'].'</td>
            $html .= '<tr>
                    <th colspan="2" style="'.$table_style.'text-align: right">发货人：</th>
                    <td colspan="3" style="'.$table_style.'text-align: left"></td>
                    <th style="'.$table_style.'text-align: right">承运人：</th>
                    <td colspan="4" style="'.$table_style.'text-align: left"></td>
                    <th colspan="2" style="'.$table_style.'text-align: right">甲方指定收货人：</th>
                    <td colspan="2" style="'.$table_style.'text-align: left"></td>
                </tr>
                <tr>
                    <th colspan="2" style="'.$table_style.'text-align: right">日期：</th>
                    <td colspan="3" style="'.$table_style.'text-align: left"></td>
                    <th style="'.$table_style.'text-align: right">电话：</th>
                    <td colspan="4" style="'.$table_style.'text-align: left"></td>
                    <th colspan="2" style="'.$table_style.'text-align: right">日期：</th>
                    <td colspan="2" style="'.$table_style.'text-align: left"></td>
                </tr>
                <tr>
                    <th colspan="2" style="'.$table_style.'text-align: right">电话：</th>
                    <td colspan="3" style="'.$table_style.'text-align: left"></td>
                    <th style="'.$table_style.'text-align: right">车牌：</th>
                    <td colspan="4" style="'.$table_style.'text-align: left"></td>
                    <th colspan="2" style="'.$table_style.'text-align: right">电话：</th>
                    <td colspan="2" style="'.$table_style.'text-align: left"></td>
                </tr>';


            //底部信息
            $html .= '<tr><th style="'.$table_style.'" colspan="14">以上数据发现不符合请当面提出，逾时恕不负责！</th></tr>';
            //$html .= '</tbody><tfoot>';
            $html .= '</tbody>';
            //底部信息
            //$html .= '<tr><th style="'.$table_style.'" colspan="15">以上数据发现不符合请当面提出，逾时恕不负责！</th></tr>';

            $html .= '</tbody></table>';
            //$html .= '</tfoot></table>';
            $html .= '</table>';

            $print_html = 'window.print();';
            if($print2 == 2)$print_html = '$("table").table2excel({
                        // 不被导出的表格行的CSS class类
                        exclude: "",
                        // 导出的Excel文档的名称
                        name: "Excel Document Name",
                        // Excel文件的名称
                        filename: "发货单",
                        //文件后缀名
                        fileext: ".xls",
                        //是否排除导出图片
                        exclude_img: false,
                        //是否排除导出超链接
                        exclude_links: true,
                        //是否排除导出输入框中的内容
                        exclude_inputs: false
                    });';
            //js
            $html .= '
                <script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/core/jquery.min.js?v=20180327"></script>
                <script src="'.config('template.tpl_replace_string')['__STATIC__'].'/common/js/jquery.table2excel.js?v='.date('Ymd').'"></script>
                <script type="text/javascript">
                    jQuery.fn.rowspan = function(colIdx=0) {
                        var that;
                        return this.each(function(row) {
                            $("td:eq(" + colIdx + ")", this).filter(":visible").each(function(col) {
                                if (that != null && $(this).html() == $(that).html()) {
                                    rowspan = $(that).attr("rowSpan");
                                    if (rowspan == undefined) {
                                        $(that).attr("rowSpan", 1);
                                        rowspan = $(that).attr("rowSpan");
                                    }
                                    rowspan = Number(rowspan) + 1;
                                    $(that).attr("rowSpan", rowspan);
                                    $(this).hide();
                                } else {
                                    that = this;
                                }
                            });
                            
                        
                        });
                    };
                    $(function() {
                        //要合并的列序号，后面数字是第几列
                        $(".group").rowspan(0); 
                        $(".group").rowspan(1);
                    });
                    '.$print_html.'
                </script>';

            echo $html;exit;
        }


        //发货单其他信息
        if(empty($address)){
            $address['id'] = '';
            $address['address_sn'] = '';
            $address['order_pid'] = $order['order_pid'];
            $address['user_nickname'] = '';
            $address['user_mobile'] = '';
            $address['address_date'] = '';
            $address['car_nickname'] = '';
            $address['car_mobile'] = '';
            $address['car_plate_number'] = $order['plate_number'];
            $address['order_nickname'] = $order['nickname'];
            $address['order_mobile'] = $order['mobile'];
            $address['order_client'] = $order['company'];
            $address['order_engineering'] = $order['engineering'];
            $address['order_date'] = date('Y-m-d');
        }

        //指定收货人
        //$deliver_note .= "  指定收货人联系方式：{$address['order_nickname']}（{$address['order_mobile']}）";

        $table_order0_head = [["订单信息[4]"]];
        $table_order0_data = [
            [
                "客户名称：",'[0]
                '.'<input class="form-control" type="text" placeholder="请填写客户名称" name="address_arr[order_client]" value="'.$address['order_client'].'">',
                "项目名称：",'[0]
                '.'<input class="form-control" type="text" placeholder="请填写项目名称" name="address_arr[order_engineering]" value="'.$address['order_engineering'].'">',
            ],
        ];
        $table_order_head = [["其他信息[6]"]];
        $table_order_data = [
            [
                "发货人：",'[0]
                '.'<input type="hidden" name="address_arr[id]" value="'.$address['id'].'"><input type="hidden" name="address_arr[order_pid]" value="'.$address['order_pid'].'"><input type="hidden" name="address_arr[address_sn]" value="'.$address['address_sn'].'"><input class="form-control" type="text" name="address_arr[user_nickname]" value="'.$address['user_nickname'].'">',
                "承运人：",'[0]
                '.'<input class="form-control" type="text" placeholder="请填写承运人" name="address_arr[car_nickname]" value="'.$address['car_nickname'].'">',
                "甲方指定收货人：",'[0]
                '.'<input class="form-control" type="text" placeholder="请填写甲方指定收货人" name="address_arr[order_nickname]" value="'.$address['order_nickname'].'">',
            ],
            [
                "日期：",'[0]
                '.$address['address_date'].'<input type="hidden" name="address_arr[address_date]" value="'.$address['address_date'].'">',
                "电话：",'[0]
                '.'<input class="form-control" type="text" placeholder="请填写承运人电话" name="address_arr[car_mobile]" value="'.$address['car_mobile'].'">',
                "日期：",'[0]
                '.'<input class="form-control" type="hidden" placeholder="请填写甲方收货日期" name="address_arr[order_date]" value="'.$address['order_date'].'">',
            ],
            [
                "电话：",'[0]
                '.'<input class="form-control" type="text" placeholder="请填写发货人电话" name="address_arr[user_mobile]" value="'.$address['user_mobile'].'">',
                "车牌：",'[0]
                '.$address['car_plate_number'].'<input type="hidden" name="address_arr[car_plate_number]" value="'.$address['car_plate_number'].'">',
                "电话：",'[0]
                '.'<input class="form-control" type="text" placeholder="请填写甲方收货人电话" name="address_arr[order_mobile]" value="'.$address['order_mobile'].'">',
            ],
        ];

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                  $("#table-list_archives").find("th").eq(8).css("width","130px");
                  $("#table-list_archives").find("th").eq(9).css("width","130px");
                  $("#table-list_archives").find("th").eq(10).css("width","130px");
                  
                  $("#table-list_archives_group").find("th").eq(4).css("width","130px");
                  $("#table-list_archives_group").find("th").eq(8).css("width","130px");
                  //监听单价设置
                  $(".group_price").bind("input propertychange", function() {
                      updatePrice($(this));
                  });
                  //监听开槽等面积设置
                  $(".area").bind("input propertychange", function() {
                      var obj = $(this);
                      var area = obj.val();
                      var type = obj.data("area-type");
                      var group = obj.data("group");
                      var toAreaSum = obj.data("toAreaSum");
                      var sum_area = 0;
                      
                      if(toAreaSum == "no"){
                          //不更新合计面积
                          sum_area = obj.val();
                      }
                      else {
                          var sum_group_area = 0;
                          //更新合计面积
                          $(".area[data-area-type="+type+"]").each(function() {
                            var each_group = $(this).data("group");
                            var val = parseFloat($(this).val());
                            if(isNaN(val)){
                                val = 0;
                            }
                            sum_area += val;
                            if(group == each_group){
                                sum_group_area += val;
                            }
                          });
                          //四舍五入保留六位小数
                          sum_area = Math.round(sum_area*1000000)/1000000;
                          sum_group_area = Math.round(sum_group_area*1000000)/100000;
                          $("#"+group+" div").text(sum_group_area);
                          $("#"+group+" input").val(sum_group_area);
                          $("."+type+"_sum").text(sum_area);
                          $("#sum_group_"+type).text(sum_area);
                      }
                      
                      //更新合计价格
                      $("."+type+"_row_area").val(sum_area);
                      $("."+type+"_val").data("one_area_sum",sum_area);
                      updatePrice($("."+type+"_val"));
                      
                  });
                  //更新合计价格
                  function updatePrice(obj) {
                      var price = obj.val();
                      var price_sum = obj.data("one_area_sum")*price;
                      //四舍五入取整
                      price_sum = Math.round(price_sum);
                      var i = obj.data("i");
                      $("#area_sum_"+i).text(price_sum);
                      
                      var sum_group_price = 0;
                      $(".group_price_all").each(function() {
                        sum_group_price += parseFloat($(this).text());
                      });
                      //四舍五入取整
                      sum_group_price = Math.round(sum_group_price);
                      $("#sum_group_price").text(sum_group_price);
                  }
                })
            </script>';

        $table_title = "档案号：{$order['order_sn']}（{$batchs}）    {$table_title}";

        return ZBuilder::make('form')
            ->setPageTitle($title) // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['complexTable:12', 'list_archives', $table_title, $table_data, $table_head],
                ['complexTable:12', 'list_archives_group', '', $table_group_data_new, $table_group_head],
                ['textarea:12', 'deliver_note', '备注','',$deliver_note],
                ['complexTable:12', 'order0_info', '', $table_order0_data, $table_order0_head],
                ['complexTable:12', 'order_info', '', $table_order_data, $table_order_head],
                ['hidden','print',1],
                ['hidden','status',input('status')],
                ['hidden','address_sn',$address_sn],
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->setExtraHtml($html_top, 'form_top')
            ->hideBtn($hideBtn)
            ->setBtnTitle(['submit' => '提交打印'])
            ->fetch();
    }
    /**
     * 审核面积表初始价格
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function archivesPriceExamine()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['o.initial_price_status','=',1];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,o.client_id as client_id2,sum(a.number) as number_sum,sum(a.one_area*a.number) as area_sum,o.id as ip_id')
            ->leftJoin('mill_order_archives a','o.id=a.order_id')
            ->where($map)
            ->group('o.id')
            ->order('o.archives_status_time desc,o.id desc')
            ->paginate();

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('面积表计价') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'a.archives_sn', '档案号', 'like'],
                ['select:2', 'o.client_id', '客户公司','','',$company],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['daterange:2', 'o.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['create_time', '工程日期','date'],
                ['archives_sn', '档案号'],
                ['client_id2','客户公司','','',$company],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['number_sum', '产品总量'],
                ['area_sum', '总面积'],
                ['initial_price_status','计价状态','callback',function($value, $data){
                    //$value = Db::name('mill_order_archives_initial_price')->where(['order_id'=>$value])->value('id');
                    //$value = empty($value)?0:1;
                    //$str = FinanceModel::$initial_price_status[$value];
                    $status = OrderModel::status_tag($value,FinanceModel::$initial_price_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['initial_price_status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('archivesPrice',['title' => '详情','href' => url('mill/finance/archivesPrice',['order_id' => '__id__']),'class'=>'btn btn-default','icon'=>''])
            ->addRightButton('backEnable',['title' => '审核通过','href' => url('archivesPriceEnable',['id' => '__id__']).'?fieldv=initial_price_status|2','class'=>'btn btn-default ajax-get','icon'=>''])
            ->addRightButton('notDisable',['title' => '审核不通过','href' => url('archivesPriceDisable',['id' => '__id__','field'=>'initial_price_status']),'icon'=>''],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'engineering'  => 150,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 面积表初始价格审核
     */
    public function archivesPriceEnable()
    {
        $id = input('param.id');
        $fieldv = input('param.fieldv');
        $fieldv = explode('|',$fieldv);
        if(false === OrderModel::where('id', $id)->setField($fieldv[0], $fieldv[1]))$this->error('审核失败，工程ID：'.$id);
        //审核人员
        OrderModel::where('id', $id)->setField($fieldv[0].'_verify_uid', UID);
        //审核时间
        OrderModel::where('id', $id)->setField($fieldv[0].'_time', time());


        $order = Db::name('mill_order')->where(['id'=>$id])->find();
        $order['company'] = Db::name('mill_client')->where(['id'=>$order['client_id']])->value('company');
        //更新调账单
        $finance = Db::name('mill_finance')->where(['order_pid'=>$order['order_pid'],'pid'=>0])->find();
        if(empty($finance)){
            //工程总金额
            $order_sum_money = FinanceModel::orderSumMoney($order['order_pid']);
            $finance_money = $order['money_str'];//定金

            $finance_add = [
                'create_time'           =>  time(),
                'update_time'           =>  time(),
                'order_pid'             =>  $order['order_pid'],
                'order_sn'              =>  $order['order_sn'],
                'engineering'           =>  $order['engineering'],
                'company'               =>  $order['company'],
                'handle'                =>  $order['archives_handle'],
                'status'                =>  1,
                //收款
                'sum_money'             =>  $order_sum_money,//工程总金额
                'deposit_money'         =>  $finance_money,//定金
                //'late_money'            =>  $late_money,//滞纳金
                //'late_time'             =>  $late_time,//滞纳金归还时间
            ];
            $finance['id'] = Db::name('mill_finance')->insertGetId($finance_add);

        }
        $order_sum_money = $order['initial_price'] - $order['old_initial_price'];
        Db::name('mill_finance')->where(['id'=>$finance['id']])->setInc('sum_money',$order_sum_money);
        Db::name('mill_order')->where(['id'=>$order['id']])->update(['old_initial_price'=>$order['initial_price']]);

        //推送消息
        $status_str = '审核';
        $content = "工程编号<span class='text-primary'>[{$order['archives_sn']}]</span>{$status_str}通过";
        $href = admin_url('archivespricelist')."?_s=a.archives_sn={$order['archives_sn']}&_o=a.archives_sn=like";
        //LogModel::send_message("面积表计价{$status_str}",$content,$href);

        $this->success('提交成功', null, '_parent_reload');

    }
    /**
     * 面积表初始价格审核不通过
     */
    public function archivesPriceDisable()
    {
        $action = new Order();
        return $action->notDisable();
    }

    /**
     * 收款记录
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function logList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $finance_id = input('finance_id');
        $map = $this->getMap();
        $map[] = ['l.finance_id','=',$finance_id];

        // 数据列表
        $data_list = Db::name('mill_finance_log')
            ->alias('l')
            ->field('l.*,o.engineering,c.company,o.order_sn')
            ->leftJoin('mill_order o','o.id=l.order_pid')
            ->leftJoin('mill_client c','c.id=o.client_id')
            ->where($map)
            ->group('l.id')
            ->order('l.id desc')
            ->paginate()
            ->each(function ($v){
                $v['money_str'] = FinanceModel::getMoneyStr($v['type'],$v['money'],true);
                $v['money'] = FinanceModel::getMoneyStr($v['type'],$v['money']);

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('收款记录（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_finance_log') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                //['text:2', 'f.order_sn', '工程编号', 'like'],
                //['text:2', 'o.engineering', '工程名称', 'like'],
                //['text:2', 'c.company', '客户公司', 'like'],
                //['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '工程号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['money_str','收款金额(元)'],
                ['note', '收款说明'],
                ['handle', '经办人'],
                /*['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,$this->_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],*/
                ['create_time', '添加日期','date'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('logAdd',['title' => '新增','href' => url('logAdd',['finance_id'=>$finance_id]),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['新增', 'font-size:24px;text-align: center;']])
            ->addRightButton('logEdit',['title' => '编辑','href' => url('logAdd',['id'=>'__id__']),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['编辑', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 新增
     * @return mixed
     */
    public function logAdd()
    {
        $id = input('id');
        $finance_id = input('finance_id');

        if ($this->request->isPost()) {
            $data = input();

            // 验证
            $rule = [
                'finance_id|标题' => 'require',
                //'type|收入类型' => 'require',
                'money|收款金额' => 'require',
                'handle|经办人' => 'require',
                'note|说明' => 'require',
            ];
            $result = $this->validate($data, $rule);
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            $data['update_time'] = time();

            if($id)$re = Db::name('mill_finance_log')->where(['id'=>$id])->update($data);
            else{
                $data['create_time'] = time();
                $re = Db::name('mill_finance_log')->insert($data);
            }

            if ($re) $this->success('操作成功','','_parent_reload');
            $this->error('操作失败');
        }

        if($id){
            $info = Db::name('mill_finance_log')
                ->alias('f')
                ->field('f.*,o.order_sn,o.engineering')
                ->leftJoin('mill_order o','o.id=f.order_pid')
                ->where(['f.id'=>$id])
                ->find();
        }
        else{
            $finance = Db::name('mill_finance')
                ->alias('f')
                ->field('f.*,o.order_sn,o.engineering')
                ->leftJoin('mill_order o','o.id=f.order_pid')
                ->where(['f.id'=>$finance_id])
                ->find();

            $info = [
                'finance_id'    =>  $finance_id,
                'order_pid'     =>  $finance['order_pid'],
                'order_sn'      =>  $finance['order_sn'],
                'engineering'   =>  $finance['engineering'],
            ];
        }

        return ZBuilder::make('form')
            ->setPageTitle('新增收款记录') // 页面标题
            ->addStatic('order_sn','工程号')
            ->addStatic('engineering','工程名称')
            ->addFormItems([ // 批量添加表单项
                ['hidden','finance_id'],
                ['hidden','order_pid'],
                ['hidden','order_sn'],
                //['radio:||||must','type', '收入类型','',['调减收入','调增收入'],1],
                ['text:||||must', 'money', '收款金额'],
                ['text:||||must', 'handle', '经办人'],
                ['textarea:||||must', 'note', '收款说明'],

            ])
            ->setFormData($info)
            ->fetch();
    }
    /**
     * 开票汇总
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function invoiceStat()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $finance_id = input('finance_id');
        $map = $this->getMap();

        // 数据列表
        $data_list = Db::name('mill_finance_invoice')
            ->alias('f')
            ->field('f.*')
            ->where($map)
            ->group('f.id')
            ->order('f.id desc')
            ->paginate()
            ->each(function ($v){
                $v['money_str'] = FinanceModel::getMoneyStr($v['type'],$v['money'],true);
                $v['money'] = FinanceModel::getMoneyStr($v['type'],$v['money']);

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('发票汇总（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_finance_invoice') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'f.order_sn', '工程编号', 'like'],
                ['text:2', 'f.engineering', '工程名称', 'like'],
                ['text:2', 'f.company', '客户公司', 'like'],
                ['text:2', 'f.handle', '经办人', 'like'],
                ['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '工程号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['model','规格'],
                ['model_num','数量'],
                ['invoice_sn','票号'],
                ['invoice_time','开票日期','date'],
                ['money_str','开票金额(元)'],
                ['note', '开票说明'],
                ['handle', '经办人'],
                /*['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,$this->_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],*/
                ['create_time', '添加日期','date'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('invoiceEdit',['title' => '编辑','href' => url('invoiceAdd',['id'=>'__id__']),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['编辑', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 开票记录
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function invoiceList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $finance_id = input('finance_id');
        $map = $this->getMap();
        $map[] = ['finance_id','=',$finance_id];

        // 数据列表
        $data_list = Db::name('mill_finance_invoice')
            ->alias('f')
            ->field('f.*')
            ->where($map)
            ->group('f.id')
            ->order('f.id desc')
            ->paginate()
            ->each(function ($v){
                $v['money_str'] = FinanceModel::getMoneyStr($v['type'],$v['money'],true);
                $v['money'] = FinanceModel::getMoneyStr($v['type'],$v['money']);

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('开票记录（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_finance_invoice') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                //['text:2', 'f.order_sn', '工程编号', 'like'],
                //['text:2', 'o.engineering', '工程名称', 'like'],
                //['text:2', 'c.company', '客户公司', 'like'],
                //['text:2', 'f.handle', '经办人', 'like'],
                //['daterange:2', 'create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['order_sn', '工程号'],
                ['engineering', '工程名称'],
                ['company', '客户公司'],
                ['model','规格'],
                ['model_num','数量'],
                ['invoice_sn','票号'],
                ['invoice_time','开票日期','date'],
                ['money_str','开票金额(元)'],
                ['note', '开票说明'],
                ['handle', '经办人'],
                /*['status','状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,$this->_status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],*/
                ['create_time', '添加日期','date'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('invoiceAdd',['title' => '新增','href' => url('invoiceAdd',['finance_id'=>$finance_id]),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['新增', 'font-size:24px;text-align: center;']])
            ->addRightButton('invoiceEdit',['title' => '编辑','href' => url('invoiceAdd',['id'=>'__id__']),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['1500px', '70%'], 'title' => ['编辑', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 新增
     * @return mixed
     */
    public function invoiceAdd()
    {
        $id = input('id');
        $finance_id = input('finance_id');

        if ($this->request->isPost()) {
            $data = input();

            // 验证
            $rule = [
                //'type|收入类型' => 'require',
                'money|调账收入' => 'require',
                'handle|经办人' => 'require',
                'note|调账说明' => 'require',
            ];
            $result = $this->validate($data, $rule);
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            $data['invoice_time'] = strtotime($data['invoice_time']);
            $data['update_time'] = time();

            if($id)$re = Db::name('mill_finance_invoice')->where(['id'=>$id])->update($data);
            else{
                $data['create_time'] = time();
                $re = Db::name('mill_finance_invoice')->insert($data);
            }

            if ($re) $this->success('操作成功','','_parent_reload');
            $this->error('操作失败');
        }

        if($id){
            $info = Db::name('mill_finance_invoice')
                ->alias('f')
                ->field('f.*,o.order_sn,o.engineering')
                ->leftJoin('mill_order o','o.order_sn=f.order_sn')
                ->where(['f.id'=>$id])
                ->find();
        }
        else{
            $finance = Db::name('mill_finance')
                ->alias('f')
                ->field('f.*,o.order_sn,o.engineering')
                ->leftJoin('mill_order o','o.id=f.order_pid')
                ->where(['f.id'=>$finance_id])
                ->find();

            $info = [
                'finance_id'      =>  $finance_id,
                'order_pid'      =>  $finance['order_pid'],
                'order_sn'      =>  $finance['order_sn'],
                'engineering'   =>  $finance['engineering'],
            ];
        }

        return ZBuilder::make('form')
            ->setPageTitle('新增开票记录') // 页面标题
            ->addStatic('order_sn','工程号')
            ->addStatic('engineering','工程名称')
            ->addFormItems([ // 批量添加表单项
                ['hidden','finance_id'],
                ['hidden','order_pid'],
                ['hidden','order_sn'],
                //['radio:||||must','type', '收入类型','',['调减收入','调增收入'],1],
                ['text:||||must', 'model', '规格'],
                ['text:||||must', 'model_num', '数量'],
                ['text:||||must', 'invoice_sn', '票号'],
                ['date:||||must', 'invoice_time', '开票日期','',date('Y-n-d')],
                ['text:||||must', 'money', '开票金额'],
                ['text:||||must', 'handle', '经办人'],
                ['textarea:||||must', 'note', '开票说明'],

            ])
            ->setFormData($info)
            ->fetch();
    }
}
